import {mainWindow} from "./index";

const { app } = require('electron');
const ExcelJS = require('exceljs');

async function createExcel(filename, contents) {
  const workbook = new ExcelJS.Workbook();

  workbook.modified = new Date();

  // 将工作簿日期设置为 1904 年日期系统
  workbook.properties.date1904 = true;

  const sheet1 = workbook.addWorksheet('Sheet1'); // 创建工作表
  const col01 = sheet1.getColumn(1);
  const col02 = sheet1.getColumn(2);
  const col03 = sheet1.getColumn(3);
  const col04 = sheet1.getColumn(4);

  col01.key = 'id';
  col02.key = 'name';
  col02.width = 30;
  col03.key = 'code';
  col04.key = 'value';
  col04.width = 20;

  contents.forEach((c, i) => {
    const row = sheet1.getRow(i + 1);
    row.values = c;
  });

  // 写文件
  workbook.xlsx.writeFile(filename).then(() => {
    mainWindow.webContents.send('createOutputFileRes', true);
  });
}

export function createOutputFile(e, content, fileName) {
  const desktopPath = app.getPath('desktop'); // 获取桌面路径

  createExcel(`${desktopPath}\\${fileName}.xlsx`, content).then();
}

/**
 * 字符串转换为十六进制
 * @param str
 * @returns {string}
 */
export function stringToHex(str) {
  let val = "";
  for(let i = 0; i < str.length; i++){
    if (val === "")
      val = str.charCodeAt(i).toString(16);
    else
      val += "," + str.charCodeAt(i).toString(16);
  }

  return val;
}

/**
 * 十六进制转换为字符串
 * @returns {string}
 * @param str
 */
export function hexToString(str) {
  let val="";
  let arr = str.split(",");
  for(let i = 0; i < arr.length; i++){
    val += String.fromCharCode(parseInt(arr[i],16));
  }

  return val;
}
